<?php

/**
 * Class provide easy SQL SELECT construction building
 *
 * Examples: 
 * <pre>
 * $select = new Adept_Db_Query_Select();
 * $select
 *     ->from('customer')
 *     ->where('id = :id');
 */
class Adept_Db_Query_Select extends Adept_Db_Query_Conditional
{

    protected $distinct = false;
    protected $columns = array();
    protected $from = array();
    protected $join = array();
    protected $group = array();
    protected $having = array();
    protected $order = array();
    protected $limitCount = null;
    protected $limitOffset = null;

    const NEW_LINE = "\n\t";

    public function __toString()
    {
        $sql = 'SELECT';
        if ($this->distinct) {
            $sql .= ' DISTINCT';
        }
        if (count($this->columns) > 0) {
            $sql .= ' ' . implode(', ', $this->columns);
        } else {
            $sql .= ' *';
        }
        $sql .= self::NEW_LINE . 'FROM ' . implode(', ', $this->from);
        if (count($this->where) > 0) {
            $sql .= self::NEW_LINE . 'WHERE ' . implode(' ', $this->where);
        }

        if (count($this->order) > 0) {
            $sql .= self::NEW_LINE . 'ORDER BY ' . implode(', ', $this->order);
        }

        if (!is_null($this->limitCount) || !is_null($this->limitOffset)) {
            $sql .= self::NEW_LINE . 'LIMIT ';
            if (!is_null($this->limitCount)) {
                $sql .= $this->limitCount;
            }
            if (!is_null($this->limitOffset)) {
                $sql .= ', ';
                $sql .= $this->limitOffset;
            }
        }

        return $sql;
    }

    public function from($from, $quotes = '')
    {
        $this->from[] = $quotes . $from . $quotes;
        return $this;
    }

    public function column($column)
    {
        $this->columns[] = $column;
        return $this;
    }

    public function columns($columns)
    {
        foreach ($columns as $column) {
            $this->column($column);
        }
        return $this;
    }

    public function having()
    {
        return $this;
    }

    public function orHaving($cond, $logic = 'AND')
    {
        return $this;
    }

    public function limit($count = null, $offset = null)
    {
        $this->limitCount = $count;
        $this->limitOffset = $offset;
        return $this;
    }

    public function order($cond, $direct = '')
    {
        $this->order[] = "{$cond} {$direct}";
        return $this;
    }

    public function orderAsc($cond)
    {
        return $this->order($cond, 'ASC');
    }

    public function orderDesc($cond)
    {
        return $this->order($cond, 'DESC');
    }

}

